package com.xk.timerapp;

import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.view.View;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.xk.timerapp.base.base.build.BaseActivityPortrait;
import com.xk.timerapp.data.AlarmClock;
import com.xk.timerapp.databinding.ActivityAlarmBinding;
import com.xk.timerapp.log.X;

public class AlarmActivity extends BaseActivityPortrait<ActivityAlarmBinding> implements SensorEventListener {
    private static final int SHAKE_THRESHOLD = 15; // 摇动阈值，可根据需要调整
    private static final int SHAKE_DELAY_MILLIS = 60*1000; // 摇动后延时的毫秒数
    private SensorManager sensorManager;
    private Sensor accelerometer;
    @Override
    protected void initData() {

    }
    MediaPlayer mediaPlayer;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(startRunable);
        handler.removeCallbacks(stopRunnable);
        if(mediaPlayer.isPlaying()){
            mediaPlayer.stop();
            mediaPlayer.release();
        }
        if(vibrator!=null){
            vibrator.cancel();
        }

        sensorManager.unregisterListener(this);
    }

    Runnable startRunable = new Runnable() {
        @Override
        public void run() {
            mediaPlayer.start();
            handler.postDelayed(stopRunnable, Integer.parseInt(alarmClock.playtime)*60000);
        }
    };
    Runnable stopRunnable = new Runnable() {
        @Override
        public void run() {
            if(mediaPlayer==null){
                return;
            }
            int times = alarmClock.alarmTimes;
            int inavatime = (int) alarmClock.alarmInterval;
            times--;
            if(times>0){
                alarmClock.alarmTimes = times;
                mediaPlayer.pause();
                handler.postDelayed(startRunable,alarmClock.alarmInterval*60*1000);
                return;
            }
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
                mediaPlayer.release();
            }
        }
    };
    Handler handler;
    AlarmClock alarmClock;
    @Override
    protected void onclick() {
       bind.tvOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
       alarmClock = getAlarmClockFromIntent(getIntent());
        // 播放铃声
        if (alarmClock.ringtoneUrl != null && !alarmClock.ringtoneUrl.isEmpty()) {
            Uri ringtoneUri = Uri.parse(alarmClock.ringtoneUrl);
            mediaPlayer = MediaPlayer.create(this, ringtoneUri);
            mediaPlayer.setLooping(true);
            handler = new Handler();
            handler.postDelayed(stopRunnable, Integer.parseInt(alarmClock.playtime)*60000);
            mediaPlayer.setOnCompletionListener(
                    mp -> {
                        mp.release();
                        handler.removeCallbacks(stopRunnable); // 防止在播放结束后又调用了stopRunnable
                    });
            mediaPlayer.start();
        }

        // 启动震动
        if (alarmClock.vibrate) {
            vibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
            if (vibrator.hasVibrator()) {
                long[] pattern = {0, 500, 1000, 500}; // 震动模式：静止-震动-静止-震动
                vibrator.vibrate(pattern,0); // -1表示不重复震动
            }
        }
    }
    Vibrator vibrator;
    private AlarmClock getAlarmClockFromIntent(Intent intent) {
        AlarmClock alarmClock = new AlarmClock();
        // 从Intent中获取是否震动的标志
        alarmClock.vibrate = intent.getBooleanExtra("should_vibrate", false);
        // 从Intent中获取铃声的URL
        alarmClock.ringtoneUrl = intent.getStringExtra("ringtone_url");
        alarmClock.playtime = intent.getStringExtra("playtime");
        alarmClock.alarmTimes = intent.getIntExtra("alarmTimes",0);
        alarmClock.alarmInterval = intent.getLongExtra("alarmInterval",0);
        // 如果有其他属性也可以类似地从Intent中获取
        return alarmClock;
    }

    @Override
    protected void initPortraitView() {
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        float x = event.values[0];
        float y = event.values[1];
        float z = event.values[2];

        float gX = x / SensorManager.GRAVITY_EARTH;
        float gY = y / SensorManager.GRAVITY_EARTH;
        float gZ = z / SensorManager.GRAVITY_EARTH;
        // 计算摇动强度
        float gForce = (float) Math.sqrt(gX * gX + gY * gY + gZ * gZ);

        if (gForce > SHAKE_THRESHOLD) {
            handler.removeCallbacks(stopRunnable); // 取消之前的延时任务
            handler.removeCallbacks(startRunable); // 取消之前的延时任务
            mediaPlayer.pause();
            handler.postDelayed(startRunable, SHAKE_DELAY_MILLIS); // 设置新的延时任务
        }
        if (y < -SensorManager.GRAVITY_EARTH) {
            // 如果设备背面朝上且闹钟处于活动状态，则停止闹钟
            finish();
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }
}